/**
 * Created by bestick on 2016/1/19.
 * 基金详情页函数库
 */
$(document).ready(function () {
    /* ================================================= 默认参数 ================================================== */

    var fundDetailURL = "/api/client/standerproductfund/showstanderproductfund";

    var fundSummaryURL = "/api/client/standerproductfund/showFundDetail";

    var fundChatURL = "/api/client/standerproductfund/showchatfund";

    var fundHqURL = "/api/manager/standerproductfund/showhq";

    var fundDailyURL = "/api/client/standerproductfund/getdailyfund";

    var fundFeeRateURL = "/api/client/redeem/getRateFund";

    var commentURL = "/api/client/comment/showproductcomment";

    var addCommentURL = "/api/client/comment/addproductcomment";

    var concernURL = "/api/client/concerned/addconcerned";

    var fundInfoMap = {
        "#fundDetail-info-temp": "#fundDetail-info",
        "#fundDetail-desc-temp": "#fundDetail-desc",
        "#fundManager-temp": "#fundManager",
        "#notice-rs-temp": "#notice-rs",
        "#rank-rs-temp": "#rank-rs"
    };

    var fundDailyMap = {
        "#fund-daily-temp": "#fund-daily"
    };

    var fundFeeRateMap = {
        "#fund-fee-rate-temp": "#fund-fee-rate"
    };

    var fundSummaryMap = {
        "#profile-rs-temp": "#profile-rs"
    };

    var commentMap = {
        "#detail-evaluate-content-temp": "#detail-evaluate-content"
    };

    var nowPage = 1;
    var count = 3;

    var jsonData = '';

    /* ================================================= 执行渲染 ================================================== */

    $.ajax({
        type: "GET",
        async: false,
        url: fundDetailURL,
        data: {
            "productId": $('.fundDetail').data("pid"),
            "t": now()
        },
        dataType: "json",
        success: function (data) {
            jsonData = data;
        }
    });

    //基金详情渲染
    doRender(
        fundDetailURL,
        {
            "productId": jsonData.data.pId,
            "t": now()
        },
        fundInfoMap,
        initFundDetail
    );

    //基金历史明细
    doRender(
        fundDailyURL,
        {
            "pId": jsonData.data.pId,
            "t": now()
        },
        fundDailyMap
    );

    //基金申购费率
    doRender(
        fundFeeRateURL,
        {
            "fundFeeId": jsonData.data.pFundId,
            "t": now()
        },
        fundFeeRateMap
    );

    //基金概况渲染
    doRender(
        fundSummaryURL,
        {
            "pId": jsonData.data.pId,
            "t": now()
        },
        fundSummaryMap
    );

    /**
     * 评论渲染
     * @param callback 当前函数作为参数，必须
     * @param nowPage 当前页面
     * @param count 每页记录条数
     * @param url 请求url
     * @param pid 产品id
     * @param map 模版id和dom的id对应的一个json串
     */
    function commentRender(callback, nowPage, count, url, pid, map) {
        doRender(
            url,
            {
                "commentBelongToProduct": pid,
                "start": (nowPage - 1) * count,
                "count": count,
                "t": now()
            },
            map,
            function (XMLHttpRequest) {
                //获取total
                var total = eval('(' + XMLHttpRequest.responseText + ')').total;
                if (total >= 0) {
                    //在目标节点后append分页组件
                    $('#detail-evaluate-content').append(genPagination(total, count, nowPage));
                    //初始化分页组件
                    initPagination(callback, nowPage, count, url, pid, map);
                }
            }
        );
    }

    //执行评论渲染
    commentRender(commentRender, nowPage, count, commentURL, jsonData.data.pId, commentMap);

    //提交评论
    $('#send-evaluate').click(function () {
        var commentContent = $('#my-comment').val();
        if (commentContent == '') {
            $(this).prev().html('亲，请您填写评论后再提交哦！').fadeIn();
            return;
        }
        doPost(
            addCommentURL,
            {
                "productId": jsonData.data.pId,
                "commentContent": commentContent
            },
            function () {
                $('#myEvaluate').modal('hide').find('#error-msg').fadeOut();
                commentRender(commentRender, nowPage, count, commentURL, jsonData.data.pId, commentMap);
            }
        );
    });

    /* ============================================== 渲染之后需要加载 ============================================== */
    /**
     * 初始化基金详情相关函数
     */
    function initFundDetail() {
        initSlider();
        initBtnStyle();
    }

    /**
     * 初始化slider
     */
    function initSlider() {
        $('input.slider').bind('slide', function (evt) {
            $(this).prev().find('.min-slider-handle').html(evt.value + '%');
        }).slider();
        $('.slider-box .slider-track').click(function () {
            $(this).find('.min-slider-handle').html($(this).parent().next('input').val() + '%');
        });
        $('.slider-box .min-slider-handle').each(function () {
            $(this).html($(this).parents('div.slider').next('input').val() + '%');
        });
    }

    /**
     * 取消按钮失焦样式
     */
    function initBtnStyle() {
        $('.btn-jcb-red').focus(function () {
            this.blur();
        });
        $('#concerned').click(function () {
            doPost(
                concernURL,
                {
                    "productId": $('.fundDetail').data("pid"),
                    "t": now()
                }
            );
        });
    }

    /* ============================================== 页面初始化 ============================================== */

    //切换折叠
    $('.title').click(function () {
        $(this).find('span').toggleClass('indicate-down');
        $(this).next().slideToggle('quick').find('.control p').eq(0).click();
        if ($(this).index() != 1) {
            var fundChartBox = $(this).next().find('div.fund-chart');
            fundChartBox.highcharts().setSize(fundChartBox.width(), fundChartBox.height());
        }
    });

    //单位净值对应的control
    $('.cValue-data-month').click(function () {
        if ($(this).hasClass('active')) {
            return false;
        }
        $(this).toggleClass('active').siblings().removeClass('active');
        var number = $(this).attr("data-month");
        var mData = monthData(Line, number);
        var first = new Date(mData[0][0][0]);
        var chang = mData[0].length - 1;
        var last = new Date(mData[0][chang][0]);
        var str = first.getMonth() + 1 + '.' + first.getDate() + '-' + (last.getMonth() + 1) + '.' + last.getDate();
        $(this).find('span.date').html(str).parent('p').siblings().find('span.date').html('');
        drawCValueChart(mData[1]);
    });

    //同类排名对应的control
    $('.rank-data-month').click(function () {
        if ($(this).hasClass('active')) {
            return false;
        }
        $(this).toggleClass('active').siblings().removeClass('active');
        var number = $(this).attr("data-month");
        var mData = monthData(Line, number);
        var first = new Date(mData[0][0][0]);
        var chang = mData[0].length - 1;
        var last = new Date(mData[0][chang][0]);
        var str = first.getMonth() + 1 + '.' + first.getDate() + '-' + (last.getMonth() + 1) + '.' + last.getDate();
        $(this).find('span.date').html(str).parent('p').siblings().find('span.date').html('');
        drawRankChart(mData[0]);
    });

    //累计收益率对应的control
    $('.rate-data-month').click(function () {
        if ($(this).hasClass('active')) {
            return false;
        }
        $(this).toggleClass('active').siblings().removeClass('active');
        var number = $(this).attr("data-month");
        var mData = monthData(Line, number);
        var first = new Date(mData[0][0][0]);
        var chang = mData[0].length - 1;
        var last = new Date(mData[0][chang][0]);
        var str = first.getMonth() + 1 + '.' + first.getDate() + '-' + (last.getMonth() + 1) + '.' + last.getDate();
        $(this).find('span.date').html(str).parent('p').siblings().find('span.date').html('');
        drawRateChart(mData[4], mData[3], mData[2]);
    });

    //tabs切换
    $('#profile').click(function () {
        $('.profile').removeClass('hidden').siblings().addClass('hidden');
    });

    $('#position').click(function () {
        $('.position').removeClass('hidden').siblings().addClass('hidden');
    });

    $('#notice').click(function () {
        $('.notice').removeClass('hidden').siblings().addClass('hidden');
    });

    $('#rank').click(function () {
        $('.rank').removeClass('hidden').siblings().addClass('hidden');
    });

    /* =============================================== 图表 ================================================= */

    var modelJcbTFundDailyDates;
    var jcbTStanderFundHqModels;

    var fundChat = syncRequest(
        fundChatURL,
        {
            "pid": jsonData.data.pId,
            "t": now()
        }
    );

    var fundHq = syncRequest(
        fundHqURL,
        {
            "t": now()
        }
    );

    //获取模型数据
    modelJcbTFundDailyDates = fundChat.modelJcbTFundDailyDates;
    jcbTStanderFundHqModels = fundHq.jcbTStanderFundHqModels;

    var ljData = modelJcbTFundDailyDates.sort().reverse();
    var hsData = jcbTStanderFundHqModels.sort().reverse();
    console.log(ljData, hsData);
    var gdLine = 0, hsLine = 0, tlLine = 0;
    var ljSize = ljData.length, hsSize = hsData.length;
    var Line = [];
    var c = (ljSize > hsSize ? ljSize : hsSize);
    for (var i = 0; i < c; i++) {
        var time = (hsData[i] == null || hsData[i] == undefined) ? ljData[i].recordedDate : hsData[i].hqDate;
        Line.push({
            "gdLine": gdLine,
            "hsLine": hsLine,
            "tlLine": tlLine,
            "pmLine": ljData[i].fundRank,
            "jzLine": ljData[i].fundCurrentValue,
            "time": time
        });
        //console.log(hsData[i].hq_date);
        if (ljData[i] != null || ljData[i] != undefined) {
            gdLine = gdLine + ljData[i].fundAccumulationValue;
            tlLine = tlLine + ljData[i].fundAverage;
        } else {
            gdLine = 0;
            tlLine = 0;
        }
        if (hsData[i] != null || hsData[i] != undefined) {
            hsLine = hsLine + hsData[i].hq_date;
            console.log(hsLine)
        } else {
            hsLine = 0;
        }
    }
    console.log("---------------重写结束--------", Line);

    function getDate(datePost) {
        return new Date(datePost.replace(/-/g, "/"));
    }

    function monthAB(date, m) {
        var newDate = new Date(date.replace(/-/g, "/"));
        var d = newDate.getDate();
        newDate.setMonth(newDate.getMonth() + m);

        if (newDate.getDate() < d)
            newDate.setDate(0);
        return newDate.getTime();
    }

    function monthData(data, m) {
        var temp = [];
        var pm = [], jz = [], tl = [], hs = [], gd = [];
        var length = data.length;
        var end = monthAB(data[0].time, -m);
        console.log("看看这个月份", -m);
        for (var i = 0; i < length; i++) {
            if (end <= getDate(data[i].time).getTime()) {
                pm.push([getDate(data[i].time).getTime(), data[i].pmLine]);
                jz.push([getDate(data[i].time).getTime(), data[i].jzLine]);
                tl.push([getDate(data[i].time).getTime(), data[i].tlLine]);
                hs.push([getDate(data[i].time).getTime(), data[i].hsLine]);
                gd.push([getDate(data[i].time).getTime(), data[i].gdLine]);
            }
        }
        temp.push(pm.sort(), jz.sort(), tl.sort(), hs.sort(), gd.sort());
        return temp;
    }

    var colors = Highcharts.getOptions().colors;
    var color_area = ['rgba(50,144,210,0.3)', 'rgba(255,0,0,0.3)', 'rgba(243,186,114,0.3)', 'rgba(0,255,0,0.3)', 'rgba(0,255,0,0.3)', 'rgba(0,255,0,0.3)', 'rgba(0,255,0,0.3)', 'rgba(0,255,0,0.3)'];
    $.each(colors, function (i) {
        colors[i] = {
            linearGradient: {x1: 0, y1: 0, x2: 0, y2: 4},
            stops: [
                [0, color_area[i]],
                [0.3, 'rgba(255,255,255,0.3)'],
                [1, color_area[i]]
            ]
        };
    });

    //单位净值
    function drawCValueChart(data) {
        $('#cValue-chart').highcharts({
            chart: {
                zoomType: 'x',
                type: 'areaspline'
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            xAxis: {
                type: 'datetime',
                labels: {
                    formatter: function () {
                        var da = new Date(this.value);
                        return da.getMonth() + 1 + "/" + da.getDate();
                    },
                    enabled: true
                }
                //tickInterval:100
            },
            tooltip: {
                crosshairs: true,
                xDateFormat: '%Y-%m-%d',
                valueSuffix: ' %',
                valueDecimals: 2
            },
            yAxis: {
                title: {
                    text: ''
                }
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                series: {
                    marker: {
                        enabled: false
                    }
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                name: fundChat.pName,
                data: data
            }]
        });
    }

    //同类排名
    function drawRankChart(data) {
        $('#rank-chart').highcharts({
            chart: {
                renderTo: 'char-window',
                zoomType: 'x',
                type: 'areaspline'
            },
            title: {
                text: '近一个月同类排行走势图',
                style: {
                    color: '#929292',
                    borderWidth: '1px',
                    borderColor: '#e4e4e4',
                    borderStyle: 'solid'
                }
            },
            subtitle: {
                text: ''
            },
            xAxis: {
                type: 'datetime',
                labels: {
                    formatter: function () {
                        var da = new Date(this.value);
                        return da.getMonth() + 1 + "/" + da.getDate();
                    },
                    enabled: true
                }
                //tickInterval:100
            },
            yAxis: {
                title: {
                    text: ''
                }
            },
            tooltip: {
                crosshairs: true,
                xDateFormat: '%Y-%m-%d',
                valueSuffix: ' 名'
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                series: {
                    marker: {
                        enabled: false
                    }
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                name: '同类排名',
                data: data
            }]
        });
    }

    //累计收益率
    function drawRateChart(data1, data2, data3) {
        $('#rate-chart').highcharts({
            chart: {
                zoomType: 'x',
                type: 'areaspline'
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            xAxis: {
                type: 'datetime',
                labels: {
                    formatter: function () {
                        var da = new Date(this.value);
                        return da.getMonth() + 1 + "/" + da.getDate();
                    },
                    enabled: true
                }
                //tickInterval:100
            },
            yAxis: {
                title: {
                    text: ''
                }
            },
            tooltip: {
                shared: true,
                crosshairs: true,
                xDateFormat: '%Y-%m-%d',
                valueDecimals: 2
            },
            legend: {
                enabled: true,
                align: 'right',
                verticalAlign: 'bottom',
                x: -10,
                symbolWidth: 12,
                symbolHeight: 12,
                symbolRadius: 6,
                itemDistance: 10,
                itemStyle: {
                    color: '#929292',
                    fontSize: '12px',
                    fontWeight: 'normal'
                },
                symbolPadding: 3
            },
            credits: {
                enabled: false
            },
            plotOptions: {
                series: {
                    marker: {
                        enabled: false
                    }
                }
            },
            series: [{
                name: fundChat.pName,
                data: data1
            },
                {
                    name: '沪深',
                    data: data2
                },
                {
                    name: '同类平均',
                    data: data3
                }]
        });
    }
});